//*********************************************************************
// Copyright (C) 2014 Hell Prototypes / www.hellprototypes.com
// 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
//********************************************************************
#include <avr/io.h>
#include "common.h"


#define VIBATOR_ADDR		0x30
#define MAGNETIC_ADDR		0x3C
#define RTC_ADDR			0xA2


bool i2c_dev_cmd(byte addr, byte reg, byte cmd);
bool i2c_dev_read(byte addr, byte start_reg, byte *buffer, byte len);

bool i2c_dev_cmd(byte addr, byte reg, byte cmd)
{
	if(!i2c_start(addr)) {
		return false;
	}

	if(!i2c_write(reg)) {
		return false;
	}
	if(!i2c_write(cmd)) {
		return false;
	}

	i2c_stop();

	return true;

}

bool i2c_dev_read(byte addr, byte start_reg, byte *buffer, byte len)
{
	byte i=0;

	if(!i2c_start(addr)) {
		return false;
	}

	if(!i2c_write(start_reg)) {
		return false;
	}

	if(!i2c_start(addr | 0x01)) {
		return false;
	}

	for(i=0; i<len-1; i++) {
		if(!i2c_read(&buffer[i], I2C_ACK)) {
			i2c_stop();
			return false;
		}
	}

	if(!i2c_read(&buffer[i], I2C_NACK)) {
		return false;
	}

	i2c_stop();

	return true;
}


bool vibator_cmd(byte reg, byte cmd)
{
	return i2c_dev_cmd(VIBATOR_ADDR, reg, cmd);
}

bool vibator_read(byte start_reg, byte *buffer, byte len)
{
	return i2c_dev_read(VIBATOR_ADDR, start_reg, buffer, len);
}

bool magnetic_cmd(byte reg, byte cmd)
{
	return i2c_dev_cmd(MAGNETIC_ADDR, reg, cmd);
}

bool magnetic_read(byte start_reg, byte *buffer, byte len)
{
	return i2c_dev_read(MAGNETIC_ADDR, start_reg, buffer, len);
}

bool rtc_read(byte start_reg, byte *buffer, byte len)
{
	return i2c_dev_read(RTC_ADDR, start_reg, buffer, len);
}


